<?php
include 'common.php';
checkLogin();

// 处理消息发送
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'send_message':
                sendMessage();
                break;
            case 'send_announcement':
                sendAnnouncement();
                break;
            case 'mute_user':
                muteUser();
                break;
            case 'unmute_user':
                unmuteUser();
                break;
            case 'mention_all':
                mentionAll();
                break;
        }
    }
}

// 发送消息
function sendMessage() {
    if (!isset($_SESSION['username'])) {
        return;
    }
    
    $username = $_SESSION['username'];
    $message = trim($_POST['message']);
    
    if (empty($message)) {
        return;
    }
    
    // 检查用户是否被禁言
    if (isUserMuted($username)) {
        $timeLeft = getMuteTimeLeft($username);
        $_SESSION['error'] = "您已被禁言，剩余时间: {$timeLeft}";
        return;
    }
    
    // 处理@提及
    $processedMessage = processMentions($message);
    
    // 保存消息
    $timestamp = date('Y-m-d H:i:s');
    $messageData = [
        'username' => $username,
        'message' => $processedMessage,
        'timestamp' => $timestamp,
        'type' => 'message',
        'original_message' => $message
    ];
    
    saveMessage($messageData);
}

// 处理@提及
function processMentions($message) {
    // 处理@全体成员
    if (strpos($message, '@全体成员') !== false || strpos($message, '@all') !== false) {
        // 只有管理员可以@全体成员
        if ($_SESSION['role'] === 'admin') {
            $message = str_replace(['@全体成员', '@all'], '<span class="mention mention-all">@全体成员</span>', $message);
            
            // 添加系统通知
            $timestamp = date('Y-m-d H:i:s');
            $systemMessage = [
                'username' => '系统通知',
                'message' => "管理员 {$_SESSION['username']} 提到了全体成员",
                'timestamp' => $timestamp,
                'type' => 'system'
            ];
            saveMessage($systemMessage);
        } else {
            $message = str_replace(['@全体成员', '@all'], '@全体成员(仅管理员可用)', $message);
        }
    }
    
    // 处理@具体用户
    preg_match_all('/@(\w+)/', $message, $matches);
    if (!empty($matches[1])) {
        $users = getUsers();
        foreach ($matches[1] as $mentionedUser) {
            if (isset($users[$mentionedUser])) {
                $message = str_replace("@{$mentionedUser}", "<span class=\"mention mention-user\">@{$mentionedUser}</span>", $message);
            }
        }
    }
    
    return $message;
}

// 发送公告
function sendAnnouncement() {
    if (!isset($_SESSION['username']) || $_SESSION['role'] !== 'admin') {
        return;
    }
    
    $message = trim($_POST['announcement']);
    
    if (empty($message)) {
        return;
    }
    
    // 保存公告
    $timestamp = date('Y-m-d H:i:s');
    $messageData = [
        'username' => '系统公告',
        'message' => htmlspecialchars($message),
        'timestamp' => $timestamp,
        'type' => 'announcement'
    ];
    
    saveMessage($messageData);
    $_SESSION['success'] = "公告发送成功";
}

// 禁言用户
function muteUser() {
    if (!isset($_SESSION['username']) || $_SESSION['role'] !== 'admin') {
        return;
    }
    
    $targetUser = trim($_POST['target_user']);
    $muteDuration = $_POST['mute_duration'];
    $customMinutes = intval($_POST['custom_minutes']);
    
    $users = getUsers();
    
    if (!isset($users[$targetUser])) {
        $_SESSION['error'] = "用户不存在";
        return;
    }
    
    if ($users[$targetUser]['role'] === 'admin') {
        $_SESSION['error'] = "不能禁言管理员";
        return;
    }
    
    $currentTime = time();
    $mutedUntil = 0;
    $durationText = '';
    
    switch ($muteDuration) {
        case '10min':
            $mutedUntil = $currentTime + 600; // 10分钟
            $durationText = '10分钟';
            break;
        case '20min':
            $mutedUntil = $currentTime + 1200; // 20分钟
            $durationText = '20分钟';
            break;
        case 'custom':
            if ($customMinutes > 0) {
                $mutedUntil = $currentTime + ($customMinutes * 60);
                $durationText = $customMinutes . '分钟';
            } else {
                $_SESSION['error'] = "请输入有效的禁言时长";
                return;
            }
            break;
        case 'permanent':
            $mutedUntil = 0; // 0表示永久禁言
            $durationText = '永久';
            break;
        default:
            $_SESSION['error'] = "请选择禁言时长";
            return;
    }
    
    $users[$targetUser]['muted'] = true;
    $users[$targetUser]['muted_until'] = $mutedUntil;
    $users[$targetUser]['mute_reason'] = $_POST['mute_reason'] ?? '违反聊天规则';
    
    if (saveUsers($users)) {
        $_SESSION['success'] = "用户 {$targetUser} 已被禁言 {$durationText}";
        
        // 添加禁言消息
        $timestamp = date('Y-m-d H:i:s');
        $reason = $users[$targetUser]['mute_reason'];
        $messageData = [
            'username' => '系统通知',
            'message' => "用户 {$targetUser} 已被管理员禁言 {$durationText}，原因: {$reason}",
            'timestamp' => $timestamp,
            'type' => 'system'
        ];
        
        saveMessage($messageData);
    } else {
        $_SESSION['error'] = "禁言操作失败";
    }
}

// 解除禁言
function unmuteUser() {
    if (!isset($_SESSION['username']) || $_SESSION['role'] !== 'admin') {
        return;
    }
    
    $targetUser = trim($_POST['unmute_user']);
    
    $users = getUsers();
    
    if (!isset($users[$targetUser])) {
        $_SESSION['error'] = "用户不存在";
        return;
    }
    
    if (!$users[$targetUser]['muted']) {
        $_SESSION['error'] = "该用户未被禁言";
        return;
    }
    
    $users[$targetUser]['muted'] = false;
    $users[$targetUser]['muted_until'] = 0;
    $users[$targetUser]['mute_reason'] = '';
    
    if (saveUsers($users)) {
        $_SESSION['success'] = "用户 {$targetUser} 已解除禁言";
        
        // 添加解除禁言消息
        $timestamp = date('Y-m-d H:i:s');
        $messageData = [
            'username' => '系统通知',
            'message' => "用户 {$targetUser} 已被管理员解除禁言",
            'timestamp' => $timestamp,
            'type' => 'system'
        ];
        
        saveMessage($messageData);
    } else {
        $_SESSION['error'] = "解除禁言操作失败";
    }
}

// @全体成员
function mentionAll() {
    if (!isset($_SESSION['username']) || $_SESSION['role'] !== 'admin') {
        return;
    }
    
    $message = trim($_POST['mention_message']);
    
    if (empty($message)) {
        $_SESSION['error'] = "请输入消息内容";
        return;
    }
    
    // 保存@全体成员消息
    $timestamp = date('Y-m-d H:i:s');
    $messageData = [
        'username' => $_SESSION['username'],
        'message' => "<span class=\"mention mention-all\">@全体成员</span> " . htmlspecialchars($message),
        'timestamp' => $timestamp,
        'type' => 'message'
    ];
    
    saveMessage($messageData);
    
    // 添加系统通知
    $systemMessage = [
        'username' => '系统通知',
        'message' => "管理员 {$_SESSION['username']} 提到了全体成员",
        'timestamp' => $timestamp,
        'type' => 'system'
    ];
    saveMessage($systemMessage);
    
    $_SESSION['success'] = "已成功@全体成员";
}

// 登出
if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: login.php");
    exit;
}

$messages = getMessages();
$users = getUsers();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>小蛋糕聊天室 © 2025</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Arial', sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, #0c0c0c 0%, #1a1a2e 100%);
            color: #e0e0e0;
            min-height: 100vh;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        header {
            text-align: center;
            padding: 20px 0;
            border-bottom: 1px solid #00ffff;
            margin-bottom: 20px;
        }
        
        h1 {
            color: #00ffff;
            font-size: 2.5rem;
            text-shadow: 0 0 10px rgba(0, 255, 255, 0.7);
            margin-bottom: 10px;
            background: linear-gradient(90deg, #00ffff, #ff00ff);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
        
        .user-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .user-welcome {
            font-size: 1.2rem;
        }
        
        .admin-badge {
            background: linear-gradient(90deg, #ff00ff, #00ffff);
            color: #000;
            padding: 5px 10px;
            border-radius: 15px;
            font-size: 0.8rem;
            font-weight: bold;
        }
        
        .logout-btn {
            background: #ff4444;
            color: white;
            padding: 8px 15px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            text-decoration: none;
        }
        
        .logout-btn:hover {
            background: #ff6666;
        }
        
        .main-content {
            display: flex;
            gap: 20px;
        }
        
        .chat-section {
            flex: 2;
            background: rgba(30, 30, 46, 0.8);
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 0 20px rgba(0, 255, 255, 0.2);
            border: 1px solid rgba(0, 255, 255, 0.3);
        }
        
        .admin-section {
            flex: 1;
            background: rgba(30, 30, 46, 0.8);
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 0 20px rgba(0, 255, 255, 0.2);
            border: 1px solid rgba(0, 255, 255, 0.3);
        }
        
        h2 {
            color: #00ffff;
            margin-bottom: 20px;
            text-align: center;
            border-bottom: 1px solid #333;
            padding-bottom: 10px;
        }
        
        .chat-messages {
            height: 400px;
            overflow-y: auto;
            padding: 15px;
            background: rgba(10, 10, 20, 0.6);
            border-radius: 5px;
            margin-bottom: 15px;
            border: 1px solid #333;
        }
        
        .message {
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 5px;
            animation: fadeIn 0.3s;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .message.user {
            background: rgba(0, 100, 255, 0.2);
            border-left: 3px solid #00ffff;
        }
        
        .message.announcement {
            background: rgba(255, 215, 0, 0.2);
            border-left: 3px solid #ffd700;
            font-weight: bold;
        }
        
        .message.system {
            background: rgba(255, 0, 0, 0.2);
            border-left: 3px solid #ff4444;
        }
        
        .message-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 5px;
            font-size: 0.9rem;
            color: #b0b0b0;
        }
        
        .message-content {
            word-wrap: break-word;
        }
        
        .mention {
            font-weight: bold;
            padding: 2px 4px;
            border-radius: 3px;
        }
        
        .mention-all {
            background: linear-gradient(45deg, #ff0000, #ff8000);
            color: white;
        }
        
        .mention-user {
            background: linear-gradient(45deg, #00ffff, #0080ff);
            color: white;
        }
        
        .send-message {
            display: flex;
            gap: 10px;
        }
        
        .send-message input {
            flex: 1;
            padding: 10px;
            border-radius: 5px;
            border: 1px solid #333;
            background: rgba(20, 20, 30, 0.8);
            color: #e0e0e0;
        }
        
        .send-message button {
            padding: 10px 20px;
            background: linear-gradient(90deg, #00ffff, #ff00ff);
            color: #000;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: bold;
        }
        
        .admin-controls {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }
        
        .admin-group {
            margin-bottom: 15px;
            padding: 15px;
            background: rgba(20, 20, 30, 0.6);
            border-radius: 8px;
            border: 1px solid #333;
        }
        
        .admin-group h3 {
            color: #00ffff;
            margin-bottom: 10px;
            font-size: 1.1rem;
        }
        
        .admin-group label {
            display: block;
            margin-bottom: 5px;
            color: #b0b0b0;
        }
        
        .admin-group input, .admin-group textarea, .admin-group select {
            width: 100%;
            padding: 8px;
            border-radius: 5px;
            border: 1px solid #333;
            background: rgba(20, 20, 30, 0.8);
            color: #e0e0e0;
            margin-bottom: 10px;
        }
        
        .admin-group button {
            width: 100%;
            padding: 10px;
            background: linear-gradient(90deg, #ff00ff, #00ffff);
            color: #000;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: bold;
        }
        
        .custom-minutes {
            display: none;
            margin-top: 5px;
        }
        
        .message {
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 15px;
            text-align: center;
        }
        
        .error {
            background: rgba(255, 0, 0, 0.2);
            border: 1px solid #ff0000;
            color: #ff6b6b;
        }
        
        .success {
            background: rgba(0, 255, 0, 0.2);
            border: 1px solid #00ff00;
            color: #90ee90;
        }
        
        .copyright {
            text-align: center;
            margin-top: 20px;
            color: #888;
            font-size: 0.9rem;
        }
        
        .user-list {
            max-height: 200px;
            overflow-y: auto;
            background: rgba(10, 10, 20, 0.6);
            border-radius: 5px;
            padding: 10px;
            margin-bottom: 15px;
        }
        
        .user-item {
            display: flex;
            justify-content: space-between;
            padding: 5px;
            border-bottom: 1px solid #333;
        }
        
        .user-muted {
            color: #ff4444;
        }
        
        @media (max-width: 768px) {
            .main-content {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>小蛋糕聊天室</h1>
            <div class="subtitle">科技感聊天体验 © 2025</div>
        </header>
        
        <div class="user-info">
            <div class="user-welcome">
                欢迎, <strong><?php echo $_SESSION['username']; ?></strong>
                <?php if ($_SESSION['role'] === 'admin'): ?>
                    <span class="admin-badge">管理员</span>
                <?php endif; ?>
            </div>
            <a href="?logout=1" class="logout-btn">退出登录</a>
        </div>
        
        <?php displayMessages(); ?>
        
        <div class="main-content">
            <div class="chat-section">
                <h2>聊天室</h2>
                <div class="chat-messages" id="chatMessages">
                    <?php foreach ($messages as $msg): ?>
                        <div class="message <?php echo $msg['type']; ?>">
                            <div class="message-header">
                                <span class="username"><?php echo htmlspecialchars($msg['username']); ?></span>
                                <span class="timestamp"><?php echo $msg['timestamp']; ?></span>
                            </div>
                            <div class="message-content">
                                <?php 
                                if ($msg['type'] === 'message') {
                                    echo $msg['message'];
                                } else {
                                    echo htmlspecialchars($msg['message']);
                                }
                                ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
                
                <form method="POST" class="send-message">
                    <input type="text" name="message" placeholder="输入消息... 使用@用户名提及他人" required>
                    <input type="hidden" name="action" value="send_message">
                    <button type="submit">发送</button>
                </form>
                
                <?php if ($_SESSION['role'] === 'admin'): ?>
                <div style="margin-top: 10px; font-size: 0.9rem; color: #888;">
                    提示: 使用 @用户名 提及用户，@全体成员 或 @all 通知所有人
                </div>
                <?php endif; ?>
            </div>
            
            <?php if ($_SESSION['role'] === 'admin'): ?>
            <div class="admin-section">
                <h2>管理员面板</h2>
                
                <!-- 用户列表 -->
                <div class="admin-group">
                    <h3>在线用户</h3>
                    <div class="user-list">
                        <?php foreach ($users as $username => $userData): ?>
                            <div class="user-item">
                                <span class="<?php echo $userData['muted'] ? 'user-muted' : ''; ?>">
                                    <?php echo htmlspecialchars($username); ?>
                                    <?php if ($userData['role'] === 'admin'): ?>
                                        <span style="color: #00ffff;">(管理员)</span>
                                    <?php endif; ?>
                                </span>
                                <span>
                                    <?php if ($userData['muted']): ?>
                                        <span style="color: #ff4444;">禁言中</span>
                                    <?php else: ?>
                                        <span style="color: #00ff00;">正常</span>
                                    <?php endif; ?>
                                </span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                
                <!-- @全体成员 -->
                <form method="POST" class="admin-group">
                    <h3>@全体成员</h3>
                    <textarea name="mention_message" placeholder="输入要通知全体成员的消息..." rows="2" required></textarea>
                    <input type="hidden" name="action" value="mention_all">
                    <button type="submit">@全体成员</button>
                </form>
                
                <!-- 发送公告 -->
                <form method="POST" class="admin-group">
                    <h3>发送公告</h3>
                    <textarea name="announcement" placeholder="输入公告内容..." rows="2" required></textarea>
                    <input type="hidden" name="action" value="send_announcement">
                    <button type="submit">发送公告</button>
                </form>
                
                <!-- 禁言用户 -->
                <form method="POST" class="admin-group">
                    <h3>禁言用户</h3>
                    <input type="text" name="target_user" placeholder="输入要禁言的用户名" required>
                    <select name="mute_duration" id="muteDuration" required>
                        <option value="">选择禁言时长</option>
                        <option value="10min">10分钟</option>
                        <option value="20min">20分钟</option>
                        <option value="custom">自定义分钟</option>
                        <option value="permanent">永久禁言</option>
                    </select>
                    <div id="customMinutes" class="custom-minutes">
                        <input type="number" name="custom_minutes" placeholder="输入分钟数" min="1" max="10080">
                    </div>
                    <input type="text" name="mute_reason" placeholder="禁言原因 (可选)">
                    <input type="hidden" name="action" value="mute_user">
                    <button type="submit">禁言用户</button>
                </form>
                
                <!-- 解除禁言 -->
                <form method="POST" class="admin-group">
                    <h3>解除禁言</h3>
                    <input type="text" name="unmute_user" placeholder="输入要解除禁言的用户名" required>
                    <input type="hidden" name="action" value="unmute_user">
                    <button type="submit">解除禁言</button>
                </form>
            </div>
            <?php endif; ?>
        </div>
        
        <div class="copyright">
            小蛋糕聊天室 © 2025 - 版权所有
        </div>
    </div>
    
    <script>
        // 自动滚动到最新消息
        function scrollToBottom() {
            const chatMessages = document.getElementById('chatMessages');
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }
        
        // 页面加载时滚动到底部
        window.onload = scrollToBottom;
        
        // 显示/隐藏自定义分钟输入
        document.getElementById('muteDuration').addEventListener('change', function() {
            const customMinutes = document.getElementById('customMinutes');
            customMinutes.style.display = this.value === 'custom' ? 'block' : 'none';
        });
        
        // 每3秒刷新消息
        setInterval(function() {
            fetch(window.location.href)
                .then(response => response.text())
                .then(html => {
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(html, 'text/html');
                    const newMessages = doc.getElementById('chatMessages');
                    document.getElementById('chatMessages').innerHTML = newMessages.innerHTML;
                    scrollToBottom();
                });
        }, 3000);
        
        // 输入框提示
        const messageInput = document.querySelector('input[name="message"]');
        if (messageInput) {
            messageInput.addEventListener('keydown', function(e) {
                if (e.key === 'Tab') {
                    e.preventDefault();
                    const start = this.selectionStart;
                    const end = this.selectionEnd;
                    this.value = this.value.substring(0, start) + '@' + this.value.substring(end);
                    this.selectionStart = this.selectionEnd = start + 1;
                }
            });
        }
    </script>
</body>
</html>